package com.app.controller.miniprogram;

import com.app.common.Result;
import com.app.common.SystemConstant;
import com.app.model.ComplainUrlModel;
import com.app.model.UserModel;
import com.app.service.UserService;
import com.app.util.TokenUtils;
import com.app.util.UploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;

@Slf4j
@Controller
@RestController
@RequestMapping("/szwq")
public class UploadController {
    @Autowired
    UserService userService;

    /**
     * 上传文件
     */
    @PostMapping("/uploadEvidence")
    public Result<Object> uploadEvidence(HttpServletRequest request, MultipartFile file) throws IOException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token过期");
        }
        UserModel user = userService.getUserByOpenid(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        if (!file.isEmpty()) {
            if (!UploadUtils.imageTypeRight(file)) {
                return Result.error(500, "文件格式错误");
            }
            //上传文件路径
            String path = "";
            path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            int lastIndexOf = fileName.lastIndexOf(".");
            String date = getRandomString2(8);
            //获取文件的后缀名 .jpg
            String suffix = fileName.substring(lastIndexOf);
            String suffix2 = fileName.substring(lastIndexOf + 1);
            File filePath = new File(path + File.separator + date + suffix);
            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //获取文件大小
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            String fileURL = "";
            fileURL = SystemConstant.DEFAULT_UPLOAD_SERVICE_URL + date + suffix;
            ComplainUrlModel model = new ComplainUrlModel();
            model.setUrl(fileURL);
            model.setAttType(suffix2);//文件后缀名
            String[] suffixType1Arr = SystemConstant.DEFAULT_type1.split(",");
            for (int i = 0; i < suffixType1Arr.length; i++) {
                if (suffix2.contains(suffixType1Arr[i])) {
                    model.setFileType(1);
                }
            }
            String[] suffixType2Arr = SystemConstant.DEFAULT_type2.split(",");
            for (int i = 0; i < suffixType2Arr.length; i++) {
                if (suffix2.contains(suffixType2Arr[i])) {
                    model.setFileType(2);
                }
            }
            String[] suffixType3Arr = SystemConstant.DEFAULT_type3.split(",");
            for (int i = 0; i < suffixType3Arr.length; i++) {
                if (suffix2.contains(suffixType3Arr[i])) {
                    model.setFileType(3);
                }
            }
            String[] suffixType4Arr = SystemConstant.DEFAULT_type4.split(",");
            for (int i = 0; i < suffixType4Arr.length; i++) {
                if (suffix2.contains(suffixType3Arr[i])) {
                    model.setFileType(4);
                }
            }
            return Result.success(model);
        } else {
            return Result.error(500, "上传失败");
        }

    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<String> upload(HttpServletRequest request,
                                 @RequestParam("file") MultipartFile file) throws IOException {

        String token = request.getHeader("authori-zation");
        if (token == null) {
            token = request.getHeader("token");
            if (token == null) {
                return Result.error(405, "token不存在");
            }
        }
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token过期");
        }
        if (!file.isEmpty()) {
            if (!UploadUtils.imageTypeRight(file)) {
                return Result.error(500, "文件格式错误");
            }
            //上传文件路径
            String path = "";
            path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            int lastIndexOf = fileName.lastIndexOf(".");
            String date = getRandomString2(8);
            //获取文件的后缀名
            String suffix = fileName.substring(lastIndexOf);

            File filePath = new File(path + File.separator + date + suffix);
            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            String imgURL = "";
            //szjy.gshwsc.com  域名
            imgURL = SystemConstant.DEFAULT_UPLOAD_SERVICE_URL + date + suffix;
            log.info("地址" + imgURL);
            return Result.success(imgURL);
        } else {
            return Result.error(500, "上传失败");
        }

    }

    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }


        }
        return sb.toString();
    }
}
